# -*- coding: utf-8 -*-
"""
@Time ： 2025/5/19 13:07
@Auth ： 九问
@File ：request_utils.py
@IDE ：PyCharm
@Email : 2750826557@qq.com
"""
import requests

import logging

logger = logging.getLogger('request_utils')  # 日志记录器


class RequestUtils:
    sess = requests.Session()  # 实例化
    public_params = {}
    base_url = "http://localhost:8000"

    def send_request(self, **kwargs):
        # 统一参数类型，仅限关键字参数

        logger.info('正在发送请求...')

        # 确保HTTP方法大写
        if 'method' in kwargs:
            kwargs['method'] = kwargs['method'].upper()
        # 自动处理JSON/data
        headers = kwargs.get('headers', {})
        if 'data' in kwargs and headers.get('Content-Type') == 'application/json':
            kwargs['json'] = kwargs.pop('data')

        params = kwargs.get('params', {}) or {}
        params.update(self.public_params)  # 合并公共参数到params
        kwargs['params'] = params

        url = kwargs.get('url', "")
        if url.startswith("http"):
            pass
        else:
            url = self.base_url + url
        kwargs['url'] = url
        files = kwargs.get('files', {})
        for name, file in files.items():
            if isinstance(file, str):  # 传入的是文件路径而不是文件对象
                files[name] = open(file, "rb")  # 将文件对象替换原来的文件路径字符串
        kwargs['files'] = files
        for k, v in kwargs.items():
            logger.info(f'    参数内容：{k}={v}')
        resp = self.sess.request(**kwargs)  # 参数长度、内容是不确定
        logger.info('收到接口响应')
        logger.info(f'    状态码={resp.status_code}')
        logger.info(f'    响应头={resp.headers}')
        logger.info(f'    响应正文={resp.text}')

        return resp
